package com.qf.data.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qf.common.constant.CacheConstant;
import com.qf.data.service.HeartBeatService;
import com.qf.data.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.swing.StringUIClientPropertyKey;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author 千锋健哥
 */
@Service
public class HeartBeatServiceImpl implements HeartBeatService {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void savePing(String productKey, String deviceKey) {
        if (StringUtils.isEmpty(productKey)
                || StringUtils.isEmpty(deviceKey)) {
            return;
        }

        String key = CacheConstant.Entity.DEVICE + CacheConstant.Suffix.PING + "_"
                + productKey + "_" + deviceKey;

        redisUtil.setKey(key, "1", 30, TimeUnit.SECONDS);
    }

    @Override
    public Boolean deviceState(String productKey, String deviceKey) {
        String key = CacheConstant.Entity.DEVICE + CacheConstant.Suffix.PING + "_"
                + productKey + "_" + deviceKey;

        String value = redisUtil.getKey(key, String.class);

        if ("1".equals(value)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Integer onLineCount(String productKey) {
        String key = CacheConstant.Entity.DEVICE + CacheConstant.Suffix.PING + "_"
                + productKey + "*";

        Set<String> keys = redisUtil.keys(key);
        if (keys != null) {
            return keys.size();
        } else {
            return 0;
        }
    }

}
